<template>
  <div class="app-role">
    <h3>库存管理</h3>
   <Query
     :items="queryColumns"
     :initial-params="queryParams"
     @query="handleQuery"
     labelWidth="100px"
   />
   <Table
     :table-columns="tableColumns"
     :table-loading="tableLoading"
     :table-data="tableData"
     :total="total"
     @pagination="handlePagination"
     :tree-props="{ children: 'children', hasChildren:'hasChildren',icon:'Plus' }"
   >
     <template #productName="{row}">
        <div class="productName_box">
          <img class="productName_img" :src="row.coverImg" />
          <div class="productName_Name">
            <div>{{ row.productName }}</div>
            <!-- <div style="color: #c4c4c3;">已售：{{ row.saleNum }}</div> -->
          </div>
        </div>
     </template>
     <template #status="{row}">
        <div>
          <span class="status-circle" :class="{
            greenStatus:row.status!=1,
            yellowStatus:row.status==1,
            }"></span>
          <span>{{ row.status==1?'待上架':'已上架' }}</span>
        </div>
     </template>
     <template #stockStatus="{row}">
      <div>
        <span class="status-circle" :class="{
          greenStatus:row.stockStatus==1,
          grayStatus:row.stockStatus!=1,
          }"></span>
        <span>{{ row.stockStatus==1?'有货':row.stockStatus==2?'部分缺货':'缺货' }}</span>
      </div>
     </template>
     <template #skuStatus="{row}">
        <div>
          <span class="status-circle" :class="{
            grayStatus:row.skuStatus!=2 && row.skuStatus!=1,
            greenStatus:row.skuStatus==1,
            yellowStatus:row.skuStatus==2,
            }"></span>
          <span>{{ row.skuStatus==1?'全部在售':row.skuStatus==2?'部分在售':'全部禁售' }}</span>
        </div>
     </template>
     <template #opt="scope">
       <el-button type="primary" link @click="handleAdd(scope.row)">补货</el-button>
     </template>
   </Table>
   <el-dialog v-model="showDialog" :title="dialogTitle" width="1080">
      <el-row>
        <el-col :span="24">
          <div style="padding: 10px 0;">
            <el-button plain type="primary" @click="getDetail()" size="default" style="margin-right: 8px">刷新</el-button>
            <span>刷新当前实际库存</span>
          </div>
        </el-col>
        <el-col :span="24" v-if="skuList.length">
          <el-table :data="skuList">
            <el-table-column label="主图" width="60">
              <template #default="{ row }">
                <div class="sku-img-wrap"  style="position: relative;">
                  <img :src="row.img" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格" min-width="80">
              <template #default="{ row }">
                {{ row.wholeName }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号" min-width="120">
              <template #default="{ row }">
                {{ row.platId }}
              </template>
            </el-table-column>
            <el-table-column label="条形码" width="120">
              <template #default="{ row }">
                {{ row.barcode }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80">
              <template #default="{ row,$index }">
                <div>
                  <span class="status-circle" :class="{
                    greenStatus:row.status==1,
                    grayStatus:row.status!=1,
                    }"></span>
                  <span>{{ row.status==1?'在售':'禁售' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="当前库存" width="80">
              <template #default="{ row }">
                {{ row.num }}
              </template>
            </el-table-column>
            <el-table-column label="改变库存(格式：+/-数字)" width="250">
              <template #default="{ row }">
                <div style="display: flex;align-items: center;">
                  <div style="width: 50px;">
                    <el-radio-group v-model="row.numType" size="default">
                      <el-radio :value="1">+</el-radio>
                      <el-radio :value="2">-</el-radio>
                    </el-radio-group>
                  </div>
                  <div>
                    <el-input-number v-model="row.newNum" :maxlength="10" :precision="0" :min="0" size="default" style="width: 120px;"></el-input-number>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="修改后库存" width="90">
              <template #default="{ row }">
                
                <span v-if="row.numType==1">{{ row.num+row.newNum }}</span>
                <span v-else>{{ row.num-row.newNum }}</span>
              </template>
            </el-table-column>
            
          </el-table>
          <!-- <el-button type="primary" size="default" style="margin:10px 0;">重置商品</el-button> -->
        </el-col>
        <el-col :span="24">
          <p style="font-size: 12px;color:#aaa; padding: 10px 0; line-height: 24px;">
            1、该商品如果为有货状态，则代表所有直购商品状态为正常的SKU不存在当前库存为0的情况<br/>
            2、该商品如果为部分缺货状态，则代表所有直购商品状态为正常的SKU有且不完全存在当前库存为0的情况<br/>
            3、该商品如果为全部缺货状态，则代表所有直购商品状态为正常的SKU的所有当前库存为0<br/>
            4、如果某个商品的某个SKU存在该SKU的当前库存小于等于预警库存且不为0时，显示有库存预警<br/>
            5、任何时候库存不得小于0<br/>
            6、如果改变库存时减少库存，会根据实际库存情况进行减少，比如库存当前库存201，减少200库存，在确认时前台销售数3，则实际库存为0，其中有正常销售减3的记录，此次操作实际减库存为198
          </p>
        </el-col>
      </el-row>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false" size="default">取消</el-button>
          <el-button type="primary" @click="handleSubmit" size="default">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="productTemeplate">
import Table from "@/components/Table/index.vue";
import Query from "@/components/Query/index.vue";
import DialogForm from '@/components/FormDialog/index.vue'
import { getGoodsList, saveGoods,changeGoodStatus,getTemplateList,getSkuStockSkuList,skuStockReplenish } from "@/api/goods";
const { proxy } = getCurrentInstance()
const tableData = ref([])
const tableData2 = ref([])
const total = ref(0)
const total2 = ref(0)
const tableLoading = ref(true)
const tableLoading2 = ref(true)
const dialogTitle = ref('')
const loading = ref(false)
const showDialog = ref(false)
const router = useRouter();
const skuList = ref([])

const formData = ref({
  productName:'',
})
const detailId = ref(null)
const data = reactive({
 tableColumns: [
   { label: "商品名称", prop: "productName",slot: 'productName',width:300},
   { label: "库存状态", prop: "stockStatus",slot: 'stockStatus' },
   { label: "SKU数", prop: "skuNum" },
   { label: "缺货SKU数", prop: "skuLackNum",},
   { label: "最近补货时间", prop: "gmtModify",width:200},
   { label: "操作",  prop: "opt", slot: 'opt',width:80},
 ],
 queryColumns: [
  { label: "商品名称", prop: "productName", type: 'input', attrs: {placeholder:'请输入'}},
 ],
 pageParams: {
  current: 1,
  size: 10
 },
 queryParams: {},
 formItems: [

 ]
})
const pageParams2 = ref({
  current: 1,
  size: 10
})
const { tableColumns, queryColumns, pageParams, queryParams, formItems } = toRefs(data)
/** 获取列表数据 */
const getList = () => {
  tableLoading.value = true
  const data  = {
     ...queryParams.value,
     ...pageParams.value,
  }
  getGoodsList(data)
  .then(res => {
    let list = res.data.records || []
     tableData.value = list
     total.value = res.data.total
  })
  .finally(() => {
     tableLoading.value = false
  })
}

getList()

/** 搜索按钮操作 */
const handleQuery = (val) => {
 queryParams.value = val
 getList()
}
/** 搜索按钮操作 */
const handleQuery2 = (val) => {
  pageParams2.value.current = 1
 getTemplateList2()
}
/** 重置按钮操作 */
const resetQuery2 = (val) => {
 pageParams2.value.current = 1
 getList()
}
const getDetail = ()=>{
  getSkuStockSkuList({ prodId:detailId.value }).then(res => {
    let data =res.data || {}
    data.map(item=>{
      item.numType = 1
      item.newNum = 0
    })
    skuList.value = data
    console.log('skuarr',skuList)
  })
}
/** 打开新增弹窗 */
const handleAdd = (row) => {
  dialogTitle.value = '补货'
  // pageParams2.value = {
  //   current: 1,
  //   size: 10
  // }
  // getTemplateList2()
  detailId.value = row.id
  getDetail()
  showDialog.value = true
}

/** 打开编辑弹窗 */
const handleEdit = (row) => {
  router.push({
    path:'/productMgmt/product/add',
    query:{
      id:row.id,
    }
  })
}
/** 获取列表数据 */
const getTemplateList2 = () => {
  tableLoading2.value = true
  const data  = {
     ...formData.value,
     ...pageParams2.value
  }
  getTemplateList(data)
  .then(res => {
     tableData2.value = res.data.records
     total2.value = res.data.total
  })
  .finally(() => {
     tableLoading2.value = false
  })
}
const selectTemeplate=(item)=>{
  router.push({
    path:'/productMgmt/product/add',
    query:{
      templateId:item.id,
    }
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
 proxy.$modal.confirm('是否确认删除此数据？').then(function() {
  saveGoods({id: row.id, delFlag: -1}).then(() => {
     getList()
     proxy.$modal.msgSuccess("删除成功")
   })
 })
}
/** 删除按钮操作 */
function handleStatus(row,status) {
 proxy.$modal.confirm('是否确认'+(status==1?'下架':'上架')+'此商品？').then(function() {
  changeGoodStatus({id: row.id, status}).then(() => {
     getList()
     proxy.$modal.msgSuccess(status==1?"下架成功":"上架成功")
   })
 })
}
const handlePagination = (val) => {
 pageParams.value = val
 getList()
}

const handleSubmit = ()=>{
  const newskuList = JSON.parse(JSON.stringify(skuList.value))
  let arr = []
  newskuList.map((item,i)=>{
    arr.push({
      skuId:item.id,
      num:item.numType==1?item.newNum:0-item.newNum
    })
  })
  skuStockReplenish(arr).then(res=>{
    console.log(11,res)
    if(res.code==200){
      showDialog.value = false
      proxy.$modal.msgSuccess("保存成功")
      getList()
    }
  })
}
</script>

<style lang="scss" scoped>
.productName_box{
  display: flex;
  align-items: center;
  .productName_img{
    width: 60px;
    height: 60px;
    object-fit: cover;
    margin-right: 8px;
  }
  span{

  }
}
.app-role {
 padding: 8px
}
.product_tem_wrap{
  display: flex;
  width: 100%;
  max-height: 400px;
  overflow: auto;
  flex-wrap: wrap;
  padding: 20px 0;
  padding-left:20px;
}
.product_tem_box{
  border: 1px solid #ddd;
  border-radius: 2px;
  cursor: pointer;
  height: 90px;
  margin-bottom: 20px;
  margin-right: 3%;
  padding: 10px;
  width: 30%;
  display: flex;
  .product_tem_img{
    width: 68px;
    height: 68px;
    margin-right: 8px;
    img{
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
  .product_tem_name{
    flex: 1;
  }
  .product_tem_name_text{
    height: 40px;
    line-height: 20px;
    margin-bottom: 6px;
    max-width: 150px;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal !important;
    word-break: break-all;
  }
  .product_tem_typeName{
    color: #c4c4c3;
  }
}
.product_tem_box:hover{
  border-color: #4a89f0;
}

:deep(.sku-img-wrap) {
  cursor: pointer;
  .el-upload--picture-card,.el-upload-list--picture-card .el-upload-list__item-actions,.el-upload-list--picture-card .el-upload-list__item{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 44px;
    height: 44px;
  }
  img{
    width: 44px;
    height: 44px;
    object-fit: contain;
    cursor: pointer;
  }
}
// 规格信息
.sku-img-wrap {

}
.sku_item_info{
  flex: 1;
  margin-left: 8px;
  .sku_item_name{
    -webkit-box-orient: vertical;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    white-space: normal !important;
    word-break: break-all;
  }
  .sku_item_type{
    color: #aaa;
  }
}
// sku详情弹窗
.skuItemInfo_box{
  width: 300px;
  margin: 0 auto;
  color: #666;
  font-size: 14px;
  .skuItemInfo_name{
    color: #000;
    font-size: 16px;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .skuItemInfo_wholeName{
    
    margin-top: 10px;
  }
  .skuItemInfo_barcode{
    margin-top: 10px;
  }
  .skuItemInfo_img{
    margin-top: 10px;
    img{
      width: 300px;
      height: 300px;
      object-fit: contain;
    }
  }
}
</style>